package com.Exam;

import java.util.Random;
import java.util.concurrent.*;

public class Exam03 {
    //编写⼀个Java程序，使⽤线程池来并⾏计算⼀个⼤数组的元素之和。
    //确保线程池中的线程能够正确协作。
    public static void main(String[] args) {
        int[] array = nums(1000); // 生成一个大数组
        int numThreads = 5; // 线程池中线程的数量

        // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

        // 将数组分成多个子数组，每个子数组由一个线程处理
        int subArraySize = array.length / numThreads;
        int startIndex = 0;
        int endIndex = subArraySize;
        Future<Integer>[] results = new Future[numThreads];
        for (int i = 0; i < numThreads; i++) {
            final int start = startIndex;
            final int end = (i == numThreads - 1) ? array.length : endIndex;
            results[i] = executorService.submit(new Callable<Integer>() {
                @Override
                public Integer call() {
                    int sum = 0;
                    for (int j = start; j < end; j++) {
                        sum += array[j];
                    }
                    System.out.println(Thread.currentThread().getName() + "的和为：" + sum);
                    return sum;
                }
            });
            startIndex = endIndex;
            endIndex += subArraySize;
        }

        // 等待所有子任务完成并计算总和
        int totalSum = 0;
        for (Future<Integer> result : results) {
            try {
                totalSum += result.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }

        // 关闭线程池
        executorService.shutdown();
        System.out.println("数组的总和是: " + totalSum);
    }

    // 生成一个随机大数组
    public static int[] nums(int size) {
        int[] array = new int[size];
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            int num = random.nextInt(10000);
            System.out.println(num);
            array[i] = num;
        }
        return array;
    }
}
